package com.fadadianqi.logistics.admin.staff.service;

import com.fadadianqi.logistics.admin.staff.dao.GroupActionDAO;
import com.fadadianqi.logistics.admin.staff.model.Action;
import com.fadadianqi.logistics.admin.staff.model.Group;
import com.fadadianqi.logistics.admin.staff.model.GroupAction;
import com.fadadianqi.cache.Cache;
import com.fadadianqi.cache.CacheFactory;
import com.fadadianqi.commons.PrimaryKeyCreator;
import com.yeqiangwei.commons.util.ValidatorHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class GroupActionService {

    private Cache cache = CacheFactory.getCache("staff");


    public void actionToGroup(Action a, Group g) {
        if (a == null || g == null) {
            return;
        }
        GroupAction ga = groupActionDAO.getWithGroupIdAndActionId(g.getId(), a.getId());
        if (ga == null) {
            ga = new GroupAction();
            ga.setActionId(a.getId());
            ga.setGroupId(g.getId());
            ga.setId(PrimaryKeyCreator.create());
            groupActionDAO.create(ga);
            cache.del("group_action_all");
        }
    }

    public void allActionToGroup(Group g) {
        List<Action> actions = actionService.findAll();
        if (ValidatorHelper.isEmpty(actions)) {
            return;
        }
        for (Action a : actions) {
            actionToGroup(a, g);
        }
    }

    public List<Action> findByGroup(Group g) {
        if (g == null) {
            return null;
        }
        List<GroupAction> gas = (List<GroupAction>) cache.get("group_action_" + g.getId());
        if (ValidatorHelper.isEmpty(gas)) {
            gas = groupActionDAO.findByGroupId(g.getId());
            cache.set("group_action_" + g.getId(), gas);
        }
        List<Action> as = new ArrayList<Action>();
        if (ValidatorHelper.isEmpty(gas)) {
            return null;
        }
        for (GroupAction ga : gas) {
            Action a = actionService.getById(ga.getActionId());
            if (a == null) {
                continue;
            }
            as.add(a);
        }
        return as;
    }

    public void delByGroup(Group group) {
        cache.del("group_action_" + group.getId());
        groupActionDAO.delByGroupId(group.getId());
    }

    @Autowired
    private ActionService actionService;

    @Autowired
    private GroupActionDAO groupActionDAO;

}
